package com.springboot_nanhua4.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import java.util.UUID;
import java.util.List; // 修正1：导入标准Java List（替换编译器工具类List）

// 修正2：修正mapper包路径（deo → mapper）
import com.springboot_nanhua4.dao.StudentMapper;
import com.springboot_nanhua4.model.Student;
import com.springboot_nanhua4.service.StudentService;
// 修正3：调整OssConfig包路径以匹配项目实际结构（org.pzy而非com.zy）
import com.springboot_nanhua4.configs.OssConfig;

@Service
//表示事务注解
@Transactional
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    // 修正4：保留字段注入，移除冗余的setter注入
    @Autowired
    private OSS oss;
    @Autowired
    private OssConfig ossConfig;


    @Override
    public Student add(Student s) {
        MultipartFile photoFile = s.getPhotoFile();// 取出上传的图片
        String originalFilename = photoFile.getOriginalFilename();// 获取文件原名
        String contentType = photoFile.getContentType();// 文件类型
        String newFileName = UUID.randomUUID().toString().replace("-", "")+"-"+originalFilename;

        String newFilePath = "student/" + newFileName;
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(ossConfig.getBucketName(), newFilePath, photoFile.getInputStream());
            oss.putObject(putObjectRequest);
            s.setPhoto(ossConfig.getUrlPrefix() + newFilePath);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("上传图片到OSS失败");
        }
        boolean b = super.save(s);
        if (!b) {
            throw new RuntimeException("添加学生失败");
        }
        return baseMapper.selectById(s.getId());
    }

    // 其他方法...


    @Override
    public void delete(int id) {
        int i = baseMapper.deleteById(id);
        if (i == 0) {
            throw new RuntimeException("删除失败");
        }

    }

    @Override
    public Student find(int id) {
        return baseMapper.selectById(id);
    }

    // ... 其余方法保持不变 ...
    @Override
    public List<Student> findList() { // 修正5：返回类型为java.util.List
        return baseMapper.selectList(null);
    }

    @Override
    public Student update(Student s) {
        int i = baseMapper.updateById(s);
        if (i > 0) {
            return baseMapper.selectById(s.getId());

        }
        throw new RuntimeException("更新失败");
    }
    // ... 以下代码未修改 ...
}